package com.reggie.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.reggie.constant.MessageConstant;
import com.reggie.dto.UserLoginDTO;
import com.reggie.entity.User;
import com.reggie.exception.UserNotLoginException;
import com.reggie.mapper.UserMapper;
import com.reggie.service.UserService;
import com.reggie.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    //设置连接路径
    public static final String LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";
    @Value("${reggie.wechat.appid}")
    private String appid;
    @Value("${reggie.wechat.secret}")
    private String secret;

    @Autowired
    private UserMapper userMapper;

    /**
     * 微信登录
     * 根据授权码获取微信用户的openid
     * @param userLoginDTO
     * @return
     */
    @Override
    public User userLogin(UserLoginDTO userLoginDTO) {
        log.info("微信用户登录，授权码：{}",userLoginDTO.getCode());
        //获取到微信的授权码：code
        String code = userLoginDTO.getCode();

        //调用微信接口服务，根据授权码获取微信用户的openid
        Map<String,String> param = new HashMap<>();
        param.put("appid",appid);
        param.put("secret",secret);
        param.put("js_code",code);
        param.put("grant_type","authorization_code");

        //数据格式
        String res = HttpClientUtil.doGet(LOGIN_URL, param);
        JSONObject jsonObject = JSON.parseObject(res);
        String openid = jsonObject.getString("openid");

        log.info("查询到微信用户的openid：{}",openid);

        //判断openID如果为null则抛出异常
        if (openid == null){
            throw new UserNotLoginException(MessageConstant.LOGIN_FAILED);
        }

        //根据openID查询用户
        User user = userMapper.getByOpenid(openid);
        //如果用户不存在，则完成自动注册
        if (user == null){
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDate.now());
            userMapper.insert(user);
        }
        return user;
    }
}
